<template>
  <div id="userManageView">
    <a-form
      :model="searchParams"
      layout="inline"
      style="justify-content: center; align-content: center; margin: 25px"
    >
      <a-form-item field="title" label="用户编号：" tooltip="请输入用户的编号">
        <a-input
          v-model="searchParams.id"
          placeholder="请输入要搜索的用户编号"
        />
      </a-form-item>
      <a-form-item field="title" label="用户名称：" tooltip="请输入用户名称">
        <a-input
          v-model="searchParams.userName"
          placeholder="请输入要搜索的用户名称"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="outline" shape="round" status="normal" @click="doSubmit"
          >搜 索
        </a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="outline" shape="round" status="normal" @click="loadData"
          >刷 新
        </a-button>
      </a-form-item>
    </a-form>
    <a-table
      :column-resizable="true"
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
        showJumper: true,
        showPageSize: true,
      }"
      @page-change="onPageChange"
      @pageSizeChange="onPageSizeChange"
    >
      <template #userAvatar="{ record }">
        <a-avatar :size="70" shape="circle">
          <img alt="userAvatar" :src="record.userAvatar" />
        </a-avatar>
      </template>
      <template #userRole="{ record }">
        <a-tag v-if="record.userRole === 'user'" color="arcoblue"
          >普通用户
        </a-tag>
        <a-tag v-if="record.userRole === 'admin'" color="green">管理员</a-tag>
      </template>
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #updateTime="{ record }">
        {{ moment(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #gender="{ record }">
        {{ genderMap[record.gender] || record.gender }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button
            shape="round"
            type="outline"
            @click="openModalForm(record.id)"
            >修改
          </a-button>
          <a-popconfirm
            content="确定要删除此题目吗?"
            type="error"
            okText="是"
            cancelText="否"
            @cancel="
              () => {
                console.log(`已取消`);
              }
            "
            @ok="doDelete(record)"
          >
            <a-button shape="round" type="outline" status="danger"
              >删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
    <a-modal
      width="30%"
      :visible="visible"
      placement="right"
      @ok="handleOk"
      @cancel="closeModel"
      unmountOnClose
    >
      <div style="text-align: center">
        <a-upload
          action="/"
          :fileList="file ? [file] : []"
          :show-file-list="false"
          @change="onChange"
          :custom-request="uploadAvatar"
          :before-upload="beforeUpload"
        >
          <template #upload-button>
            <a-avatar :size="70" shape="circle">
              <img alt="头像" :src="userAvatarImg || userInfo?.userAvatar" />
            </a-avatar>
          </template>
        </a-upload>
      </div>
      <a-form
        label-align="right"
        title="个人信息"
        style="max-width: 480px; margin: 0 auto"
      >
        <a-form-item field="名称" label="名称 :">
          <a-input v-model="userInfo.userName" placeholder="请输入用户名称" />
        </a-form-item>
        <a-form-item field="账号" label="账号 :">
          <a-input v-model="userInfo.userAccount" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item field="用户角色" label="角色 :">
          <a-select v-model="userInfo.userRole" placeholder="请输入用户角色">
            <a-option value="admin">管理员</a-option>
            <a-option value="user">普通用户</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="性别" label="性别 :">
          <a-select v-model="userInfo.gender" placeholder="请选择性别">
            <a-option
              v-for="option in genderOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="userProfile" label="简介 :">
          <a-textarea v-model="userInfo.userProfile" placeholder="请输入简介" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import { useRouter } from "vue-router";
import { FileItem, Message } from "@arco-design/web-vue";
import {
  FileControllerService,
  User,
  UserControllerService,
} from "../../../generated";

const router = useRouter();
const tableRef = ref();
const file = ref();

const visible = ref(false);
const userInfo = ref<User>();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref({
  id: undefined,
  userName: "",
  pageSize: 10,
  current: 1,
});

// 性别映射
const genderMap = {
  0: "男",
  1: "女",
  2: "未知",
};

// 性别选项
const genderOptions = [
  { value: 0, label: "男" },
  { value: 1, label: "女" },
  { value: 2, label: "未知" },
];

const loadData = async () => {
  const res = await UserControllerService.listUserByPageUsingPost({
    ...searchParams.value,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

watchEffect(() => {
  loadData();
});

onMounted(() => {
  loadData();
});

const columns = [
  {
    title: "编号",
    dataIndex: "id",
    align: "center",
  },
  {
    title: "账号",
    dataIndex: "userAccount",
    align: "center",
  },
  {
    title: "名称",
    dataIndex: "userName",
    align: "center",
  },
  {
    title: "头像",
    slotName: "userAvatar",
    align: "center",
    width: 64,
  },
  {
    title: "简介",
    dataIndex: "userProfile",
    align: "center",
  },
  {
    title: "性别",
    slotName: "gender",
    align: "center",
  },
  {
    title: "角色",
    slotName: "userRole",
    align: "center",
  },
  {
    title: "创建时间",
    slotName: "createTime",
    align: "center",
  },
  {
    title: "更新时间",
    slotName: "updateTime",
    align: "center",
  },
  {
    title: "操作",
    slotName: "optional",
    align: "center",
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const onPageSizeChange = (size: number) => {
  searchParams.value = {
    ...searchParams.value,
    pageSize: size,
  };
};

const openModalForm = async (userId: any) => {
  const res = await UserControllerService.getUserByIdUsingGet(userId);
  console.log("res:", res.data);
  userInfo.value = res.data;
  console.log(userInfo.value);
  visible.value = true;
};

const doDelete = async (user: User) => {
  const res = await UserControllerService.deleteUserUsingPost({
    id: user.id,
  });
  if (res.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败");
  }
};

const doSubmit = () => {
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

let userAvatarImg = userInfo.value?.userAvatar;

// 修改后的上传方法
const uploadAvatar = async (options: any) => {
  const { fileItem } = options;
  if (!fileItem || !fileItem.file) {
    Message.error("请先选择有效的文件");
    return;
  }

  try {
    const formData = new FormData();
    formData.append("file", fileItem.file); // 这里改为 fileItem.file

    const res = await FileControllerService.uploadFileUsingPost(formData);

    if (res.code === 0) {
      userAvatarImg = res.data;
      Message.success("上传成功");
      if (userInfo.value) {
        userInfo.value.userAvatar = res.data;
      }
    } else {
      Message.error("上传失败: " + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("上传错误:", error);
    Message.error("上传失败: " + (error.message || "未知错误"));
  }
};

const handleOk = async () => {
  try {
    const res = await UserControllerService.updateUserUsingPost({
      ...userInfo.value,
      userAvatar: userAvatarImg || userInfo.value?.userAvatar,
    });

    if (res.code === 0) {
      Message.success("更新成功！");
      visible.value = false;
      loadData(); // 刷新数据
    } else {
      Message.error("更新失败！" + (res.message || ""));
    }
  } catch (error) {
    console.error("更新错误:", error);
    Message.error("更新失败！");
  }
};
const beforeUpload = (file: File) => {
  const validTypes = ["image/jpeg", "image/png", "image/gif"];
  if (!validTypes.includes(file.type)) {
    Message.error("只支持JPEG、PNG或GIF格式的图片");
    return false;
  }
  if (file.size > 2 * 1024 * 1024) {
    Message.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};
const closeModel = () => {
  visible.value = false;
};

const onChange = (fileItem: FileItem) => {
  // 仅更新file引用，验证由beforeUpload处理
  file.value = fileItem;
};
</script>

<style scoped>
#userManageView {
  padding: 5px;
  box-shadow: 0px 0px 10px rgba(35, 7, 7, 0.21);
  border-radius: 10px;
}
</style>
